﻿package net.wangit.view.unit.util;

import java.util.Map;

import net.wangit.MapList;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.framework.config.DomainsSettings;
import net.wangit.framework.session.AgileSession;
import net.wangit.util.Checker;
import net.wangit.view.element.ElementComponent;
import net.wangit.view.unit.UnitComponent;


public class ValidationProcessor {

	public ValidationProcessor() {
	}

	public static void setInvalidFields(ActionContext ac, UnitComponent uc) {
		AgileSession session = ActionContextHelper.getSession(ac);
		Map invalidFields = session.getInvalidFields();
		if (invalidFields == null)
			return;
		MapList fields = (MapList) invalidFields.get(uc.getId());
		if (fields == null)
			return;
		String markStyle = DomainsSettings.getMarkStyle(uc.getDomain());
		for (int i = 0; i < uc.size(); i++) {
			ElementComponent ec = uc.getElementComponent(i);
			String id = ec.getId();
			for (int j = 0; j < fields.size(); j++)
				if (fields.getRow(j).get(id) != null) {
					String attribute = ec.getCustom();
					ec.setCustom(j, attribute != null ? (new StringBuilder(
							String.valueOf(attribute))).append(markStyle)
							.toString() : markStyle);
				}

		}

	}

	public static void setInvalidField(ActionContext ac, UnitComponent uc,
			ElementComponent ec) {
		AgileSession session = ActionContextHelper.getSession(ac);
		Map invalidFields = session.getInvalidFields();
		if (invalidFields == null)
			return;
		MapList fields = (MapList) invalidFields.get(uc.getId());
		if (Checker.isEmpty(fields))
			return;
		if (fields.getRow(0).get(ec.getId()) != null) {
			String markStyle = DomainsSettings.getMarkStyle(uc.getDomain());
			String attribute = ec.getCustom();
			ec.setCustom(attribute != null ? (new StringBuilder(String
					.valueOf(attribute))).append(markStyle).toString()
					: markStyle);
		}
	}

	private static boolean isFailed(AgileSession session, String queryUnitId) {
		Map invalidFields = session.getInvalidFields();
		if (invalidFields == null) {
			return false;
		} else {
			MapList fields = (MapList) invalidFields.get(queryUnitId);
			return !Checker.isEmpty(fields);
		}
	}
}
